// ==UserScript==
// @name         ku3.6.3
// @namespace    http://www.baidu.com/
// @version      3.6.3
// @description  ku_Tx
// @author       ku
// @match        *://pay.qq.com/h5/index.shtml*
// @match      *://pay.qq.com/h5/shop.shtml?*
// @match      *://pay.qq.com/h5/shop.shtml#*
// @match      *://pay.qq.com/h5/shop.shtml*
// @match        *://pay.qq.com/midas/minipay_v2/views/cpay/game.shtml*
// @match        *://pay.qq.com/paygame/index.shtml*
// @match        *://xinyue.qq.com/*
// @match        *://bgw.xinyue.qq.com/*
// @match        https://bgw.xinyue.qq.com/mall.api/UpdateCartItem
// @match        *://act.xinyue.qq.com/*
// @match        *://pay.qq.com/midas/minipay_v2/views/cpay/goods.shtml*
// @match        *://pay.qq.com/ipay/mobile-game/index.shtml?*
// @match        *://vipzx.qq.com/*
// @match        *://pay.qq.com/s/one?*
// @match        *://pagedoo.pay.qq.com/*
// @match        *://act.daoju.qq.com/act/*
// @connect      *
// @license      MIT
// @grant        GM_info
// @grant        unsafeWindow
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_getResourceText
// @grant        GM_xmlhttpRequest
// @grant        GM_setClipboard
// @grant        GM_getResourceURL
// @require      https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js
// @require      https://cdn.jsdelivr.net/npm/js-base64@3.7.5/base64.js
// @require      https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js
// @resource     CxSecretsFont https://static.muketool.com/scripts/cx/v2/fonts/cxsecret.json
// @resource     Layui https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.8/css/layui.min.css
// @resource     LayuiIconFont-woff2 https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.8/font/iconfont.eot
// @resource     LayuiIconFont-woff https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.8/font/iconfont.woff
// @resource     LayuiIconFont-ttf https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.8/font/iconfont.ttf
// ==/UserScript==




var _self = unsafeWindow,
    url = location.pathname,
    top = _self;

GM_addStyle(`
@import url(${GM_getResourceURL('Layui')});
`);

GM_addStyle(`
@font-face {
font-family: 'layui-icon';
src: url(${GM_getResourceURL('LayuiIconFont-woff2')}) format('woff2'),
 url(${GM_getResourceURL('LayuiIconFont-woff')}.woff) format('woff'),
 url(${GM_getResourceURL('LayuiIconFont-ttf')}) format('truetype');
font-weight: normal;
font-style: normal;
}

`);

var $ = _self.jQuery || top.jQuery,
    parent = _self == top ? self : _self.parent,
    Ext = _self.Ext || parent.Ext || {},
    UE = _self.UE,
    Base64 = self.Base64,
    vjs = _self.videojs;

// 创建 panel 的 HTML 结构
var panelHTML1 = `
     <style>
        .qr-code-txt {
            text-align: center;
            margin-bottom: 7px;
            font-family: 'helvetica neue', 'hiragino sans gb', PingFangSC-Light, Arial, tahoma, 'microsoft yahei ui', 'microsoft yahei', '微软雅黑', simsun, sans-serif;
            font-size: 14px;
        }

        .qr-code-area .qr-code-container {
            position: relative;
            width: 140px;
            height: 140px;
            display: inline-block;
            padding: 9px;
            border: 1px solid #e5e5e5;
        }

        .qr-code-area {
            text-align: center;
        }

        .qr-code-area .qr-code-container.qq {
            border-bottom-color: #3387ef;
        }

        .qr-code-txt .icon-qq,
        .qr-code-txt .icon-wx {
            margin-right: 4px;
        }

        em {
            font-style: normal;
        }

        .icon-qq {
            background-image: url(https://midas.gtimg.cn/midas/minipay_v2/images/sprite@2x.c6e1a4965de7a4069e10e6f1bb463a8c.png);
            background-position: -69px -81px;
            background-size: 226px 210px;
            width: 14px;
            height: 17px;
        }

        .qr-code-txt em {
            font-size: 20px;
            font-weight: 400;
            margin: 0 2px;
        }

        #container {
            margin: 0 auto;
        }
    </style>
    <div 
       id="draggablePanel"
        style="display: block;z-index: 99999; position: fixed; top: 0px; left:0px; background-color: #999; border: 1px solid black; padding: 5px;">
       <div>
       <button id="showHideButton1">Hide</button>
       <span id="currentAccount">${GM_getValue("currentAccount") != undefined ? GM_getValue("currentAccount") : ""}</span>
       </div> 
        <div id="panel1" style="display: block;" >
            <div>
                充值数：<input type="text" id="chongPrice" value="" style="width: 120px;">
            </div>
            <div>
                <span id="result"></span>
            </div>
            <div>
                强改数：<input type="text" id="editableNumber" value="" style="width: 120px;">
            </div>
            <div>
                总充数：<input type="text" id="totalPrice" value="` + (GM_getValue("totalPrice") != undefined ? GM_getValue("totalPrice") : "") + `" style="width: 120px;">
            </div>
             <div>
               已到账：<input type="text" id="bookedPrice" value="` + (GM_getValue("bookedPrice") != undefined ? GM_getValue("bookedPrice") : "0") + `"  style="width: 120px;">
            </div>
            <div>
                在途数：<input type="text" id="inTransitPrice" value="` + (GM_getValue("inTransitPrice") != undefined ? GM_getValue("inTransitPrice") : "0") + `"  style="width: 120px;">
            </div>
            <div>
                还需充：<input type="text" id="needPrice" value="` + (GM_getValue("needPrice") != undefined ? GM_getValue("needPrice") : "") + `"  style="width: 120px;">
            </div>
            <div>
                账户参：<input type="text" id="accountCK" value="` + (GM_getValue("accountCK") != undefined ? GM_getValue("accountCK") : "") + `" style="width: 120px;">
            </div>
            <div>
                <button id="payButton">保存</button>
                <button id="clearButton">清除</button>
                <button id="gotovip">心悦</button>
                <button id="start">中心</button>
                <button id="getAccount">获取</button>
            </div>
        </div>
    </div>
 `


    ;


var panelHTML2 = `
 <style>
    .qr-code-txt {
        text-align: center;
        margin-bottom: 7px;
        font-family: 'helvetica neue', 'hiragino sans gb', PingFangSC-Light, Arial, tahoma, 'microsoft yahei ui', 'microsoft yahei', '微软雅黑', simsun, sans-serif;
        font-size: 14px;
    }

    .qr-code-area .qr-code-container {
        position: relative;
        width: 140px;
        height: 140px;
        display: inline-block;
        padding: 9px;
        border: 1px solid #e5e5e5;
    }

    .qr-code-area {
        text-align: center;
    }

    .qr-code-area .qr-code-container.qq {
        border-bottom-color: #3387ef;
    }

    .qr-code-txt .icon-qq,
    .qr-code-txt .icon-wx {
        margin-right: 4px;
    }

    em {
        font-style: normal;
    }

    .icon-qq {
        background-image: url(https://midas.gtimg.cn/midas/minipay_v2/images/sprite@2x.c6e1a4965de7a4069e10e6f1bb463a8c.png);
        background-position: -69px -81px;
        background-size: 226px 210px;
        width: 14px;
        height: 17px;
    }

    .qr-code-txt em {
        font-size: 20px;
        font-weight: 400;
        margin: 0 2px;
    }

    .container {
        margin: 0 auto;
    }
</style>
<div 
    style="display: block;z-index: 99999; position: fixed; top: 60%; left: 50%; transform: translate(-50%, -50%); background-color: white; border: 1px solid black; padding: 5px;">
    <div style="text-align: end;">
        <button id="showHideButton2">Hide</button>
        <button id="renewalButton">更换</button>
    </div>
    <div id="panel2" class="container" style="margin:80px 40px">
        <div style="text-align: center;margin-bottom: 20px;"><span>过期时间：</span><span id="lastTime">time2</span></div>
        <div id="capture" style="padding: 12px;width:195px;margin: 0 auto;">
            <div class="qr-code-txt">
                <span class="icon-qq">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                手Q扫码，支付
                <em id="payNumber">5</em>
                <input type="hidden" id="payNumberHidden" value="5">
                <input type="text" id="editInput"  style="display: none;">
                元
            </div>
            <div class="qr-code-area">
                <div class="qr-code-container qq">
                    <div id="qrcode" style="width:140px; height:140px; margin-top:0px;"
                        title="https://myun.tenpay.com/mqq/pay/index.shtml?_wv=1027&amp;app_jump=1&amp;t=">
                        <img id="qrImg" width="140px" src="" style="display: block;">
                    </div>
                </div>
                <div class="qr-code-container qq" style="display: none;"></div>
            </div>
        </div>
        <div style="text-align: center;margin-top: 20px;"><span>参数:</span><input id="fullParam" type="text"><button id="copyfullParam">复制</button></div>
    </div>
</div>
`;

// top.addEventListener("message", event => {
//     if (event.data.type === "save") {
//         if(event.data.kuUrl == "" ){
//             alert("请到账号管理获取URL");return;
//         }
//         GM_setValue("kuUrl", event.data.kuUrl);
// 		GM_setValue("upNums", event.data.upNums);
//         alert("保存成功ok");
//     } else if(event.data.type === "start"){
//         if(event.data.kuUrl == "" ){
//             alert("请到账号管理获取URL");return;
//         }
//         GM_setValue("kuUrl", event.data.kuUrl);
//         startJob();
//     }
// }, false);
// 判断当前页面是否是父页面
if (window.top === window) {
    // 在父页面插入panelHTML
    if (!document.getElementById('panel')) {

        document.body.insertAdjacentHTML('beforeend', panelHTML1);
        // 获取 panel1 和按钮元素
        var panel1 = document.getElementById('panel1');
        var showHideButton1 = document.getElementById('showHideButton1');
        showHideButton1.style.color = 'red';
        panel1.style.zIndex = 99999;
        panel1.style.width = '220px';
        // 添加按钮点击事件
        showHideButton1.addEventListener('click', function () {
            if (panel1.style.display === 'none') {
                panel1.style.display = 'block';
                showHideButton1.textContent = '关闭';
            } else {
                panel1.style.display = 'none';
                showHideButton1.textContent = '显示';
            }
        });

        document.getElementById("payButton").addEventListener("click", function () {
            //保存总充值数量
            var totalPrice = parseInt(document.getElementById("totalPrice")?.value, 10);
            GM_setValue("totalPrice", totalPrice);
            //保存已到账数量
            var bookedPrice = eval(document.getElementById("bookedPrice")?.value);
            GM_setValue("bookedPrice", bookedPrice);
            //保存在途数量
            var inTransitPrice = eval(document.getElementById("inTransitPrice")?.value);
            GM_setValue("inTransitPrice", inTransitPrice);
            //保存还需充值数量
            GM_setValue("needPrice", totalPrice - bookedPrice - inTransitPrice);
            //保存 goUrl
            GM_setValue("accountCK", document.getElementById("accountCK")?.value);
            alert("保存成功");
        });

        // 清除按钮点击事件
        document.getElementById("clearButton").addEventListener("click", function () {
            GM_setValue("totalPrice", "");
            GM_setValue("bookedPrice", "");
            GM_setValue("inTransitPrice", "");
            GM_setValue("needPrice", "");
            GM_setValue("accountCK", "");
            GM_setValue("currentAccount", "");
            alert("清除成功");
        });

        //去心悦
        // document.getElementById("gotovip").addEventListener("click", function () {
        //     const parsed = parseCookie(document.cookie)
        //     const ck=`appid=${parsed.appid};acctype=${parsed.acctype};openid=${parsed.openid};access_token=${parsed.access_token}`;
        //     GM_setValue("vipck", ck);
        //     top.location.href = "https://xinyue.qq.com/";
        // });
        //
        document.getElementById("gotovip").addEventListener("click", function () {
            var accountCK = document.getElementById("accountCK")?.value;
            GM_setValue("accountCK", accountCK);
            // 将字符串转换为对象
            const params = accountCK.split(";").reduce((acc, pair) => {
                const [key, value] = pair.split("=");
                acc[key] = value;
                return acc;
            }, {});
            // 构造目标字符串
            const isWx = params["pay_mobile_account"] === 'wx';
            const appid = "101502376"; // 固定值
            const acctype = isWx ? "wx" : "qc"; // 固定值
            const openid = isWx ? params["pay_wechat_openid"] : params["midas_txcz_openid"]||params["pay_openid"];
            const access_token = isWx ? params["pay_wechat_access_token"] : params["midas_txcz_openkey"]||params["pay_openkey"];
            const ck = `appid=${appid};acctype=${acctype};openid=${openid};access_token=${access_token}`;
            setCookies(ck);
            top.location.href = "https://xinyue.qq.com/";

        });

        // 添加开始按钮点击事件
        document.getElementById("start").addEventListener("click", function () {
            var accountCK = document.getElementById("accountCK")?.value;
            GM_setValue("accountCK", accountCK);
            //适配微信
            const accountParams = accountCK.split(";").reduce((acc, pair) => {
                const [key, value] = pair.split("=");
                acc[key] = value;
                return acc;
            }, {});

            // 构造目标字符串
            const isWx = accountParams["pay_mobile_account"] === 'wx';
            // pay_mobile_account=wx;pay_mobile_game_account=wx;pay_wechat_openid=odFzSjvWTtsF-W6omzb4BQ_qJnw8;pay_wechat_access_token=89_303nGIi_Oxl-uYlZYScOgail0r4Oa7SBGDBsHNikAFnCVWk7QUdcNXn1vFDfOkWL0kIDqDTXgIq1vensGBoynZCSmuGUNWuggytud4tJ-FQ;refresh_token=89_cculHbmNC3Yqf-oQma0w6mKGtmpm69BML6InronWhC9ABqN8ZDc-08VBHP64ihRpOTc8UYW7RHv_9SC0YoI9ZJIRzDfBEqdfWd1rmhA5BYg;client=1.7.0;
            //https://pay.qq.com/h5/index.shtml?_refer=&openid=odFzSjvWTtsF-W6omzb4BQ_qJnw8&openkey=89_303nGIi_Oxl-uYlZYScOgail0r4Oa7SBGDBsHNikAFnCVWk7QUdcNXn1vFDfOkWL0kIDqDTXgIq1vensGBoynZCSmuGUNWuggytud4tJ-FQ&sessionid=hy_gameid&sessiontype=wc_actoken&wxAppid2=wx951bdcac522929b6&r=0.2037229703850334#/
            const openid = isWx ? accountParams["pay_wechat_openid"] : accountParams["midas_txcz_openid"]||accountParams["pay_openid"];
            const access_token = isWx ? accountParams["pay_wechat_access_token"] : accountParams["midas_txcz_openkey"]||accountParams["pay_openkey"];
            const wxAppid2 = "wx951bdcac522929b6"
            const sessionid = isWx ? "hy_gameid" : "openid"
            const sessiontype = isWx ? "wc_actoken" : "kp_accesstoken"
            // const gotoQQUrl = `https://pay.qq.com/h5/index.shtml?_refer=&openid=${openid}&openkey=${access_token}&sessionid=${sessionid}&sessiontype=${sessiontype}&r=0.62671995162963867#/`;
            const gotoWXUrl = `https://pay.qq.com/h5/index.shtml?_refer=&openid=${openid}&openkey=${access_token}&sessionid=${sessionid}&sessiontype=${sessiontype}&wxAppid2=${wxAppid2}&r=0.2037229703850334#/`;

            if(isWx){
                top.location.href=gotoWXUrl
            }else{
                const txcz_qc_loginstate=`{"qq_appid":"101502376","openid":"${openid}","openkey":"${access_token}"}`;
                const qqckString = `openid=${openid};access_token=${access_token}; appid=101502376; acctype=qc;__qc__k=TC_MK=${access_token};txcz_qc_loginstate=${txcz_qc_loginstate}`;
                setQQCookies(qqckString)
                top.location.href = "https://pay.qq.com/h5/shop.shtml?pf=2199&disable_continuous_month=1&_refer=&r=0.005265764038518084#/";
            }
        });

        // 添加获取按钮点击事件
        document.getElementById("getAccount").addEventListener("click", function () {
            GM_xmlhttpRequest({
                method: 'GET',
                url: "https://dkapi.toyong.cn/fras/game/gameaccount/list?t=1737788144561&page=1&limit=1&note=&category=%E6%96%B0%E5%BB%BA",
                headers: {
                    "Content-Type": "application/x-www-form-urlencodeapplication/json",
                    "token": "0fb7a76fee0bda0e2070d2d77dc35e64"
                },
                onload(xhr) {
                    // console.log("xhr.responseText", xhr.responseText);
                    var resp = JSON.parse(xhr.responseText);
                    if (resp.code == 0) {
                        const { accountId, note, quantity, accountCk, accountNumber } = resp.page.list[0];
                        document.getElementById("accountCK").value = accountCk;
                        document.getElementById("totalPrice").value = quantity;
                        document.getElementById("currentAccount").textContent = note;
                        //保存总充值数量
                        GM_setValue("totalPrice", quantity);
                        //保存 CK
                        GM_setValue("accountCK", accountCk);
                        //保存当前账号
                        GM_setValue("currentAccount", note);
                        //设置当前账号的状态
                        GM_xmlhttpRequest({
                            method: 'POST',
                            url: "https://dkapi.toyong.cn/fras/game/gameaccount/update",
                            headers: {
                                "Content-Type": "application/json",
                                "token": "0fb7a76fee0bda0e2070d2d77dc35e64"
                            },
                            data: JSON.stringify({
                                "t": 1737789535612, "accountId": accountId, "note": note, "quantity": quantity, "accountNumber": accountNumber, "accountCk": accountCk, "category": "在途"
                            }),
                            onload(xhr) {
                                var resp = JSON.parse(xhr.responseText);
                                if (resp.code == 0) {
                                    alert("获取成功");
                                }
                            }
                        });
                    } else {
                        alert(resp.msg);
                    }
                }
            });

        });


        document.getElementById("chongPrice").addEventListener("input", function () {
            // 获取用户输入的充值数
            var chongPrice = parseInt(document.getElementById("chongPrice").value, 10);
            if (isNaN(chongPrice)) {
                document.getElementById("editableNumber").value = "请输入有效的数字";
                return;
            }
            // 被乘数组
            var multiplier = [6, 30, 68, 128, 198, 328, 648, 1296];
            // 初始化最优结果
            var bestDifference = Infinity; // 最小差值
            var bestMultiplier = 0;        // 最优倍数
            var bestBase = 0;              // 最优被乘数
            // 遍历被乘数组，找到最优组合
            multiplier.forEach(function (base) {
                var multiplier = Math.floor(chongPrice / base); // 计算整数倍
                var result = multiplier * base;                // 计算接近的结果
                var difference = Math.abs(chongPrice - result); // 计算误差

                // 如果当前误差更小，则更新最优结果
                if (difference < bestDifference) {
                    bestDifference = difference;
                    bestMultiplier = multiplier;
                    bestBase = base;
                }
            });
            GM_setValue("buy_quantity", chongPrice);
            // 计算最终结果
            var total = bestMultiplier * bestBase;
            // 更新页面显示
            document.getElementById("editableNumber").value = bestMultiplier;
            //更新强改数
            // GM_setValue("upNums",bestMultiplier);
            document.getElementById("result").innerText =
                `档位:${bestBase}*${bestMultiplier}=${total}`;
        });



        // 增加移动事件
        var draggablePanel = document.getElementById("draggablePanel");
        var offsetX, offsetY;

        function startDrag(e) {
            // 如果点击的是输入框、按钮、文本区域或下拉菜单，则不触发拖动
            if (e.target.closest('input, button, textarea, select')) {
                return;
            }
            e.preventDefault();
            var evt = e.touches ? e.touches[0] : e;
            offsetX = evt.clientX - draggablePanel.offsetLeft;
            offsetY = evt.clientY - draggablePanel.offsetTop;

            if (e.touches) {
                document.addEventListener('touchmove', moveDrag, { passive: false });
                document.addEventListener('touchend', endDrag);
            } else {
                document.addEventListener('mousemove', moveDrag);
                document.addEventListener('mouseup', endDrag);
            }
        }

        function moveDrag(e) {
            e.preventDefault();
            var evt = e.touches ? e.touches[0] : e;
            draggablePanel.style.transform = ''; // 清除 transform，确保 left 和 top 生效
            draggablePanel.style.left = (evt.clientX - offsetX) + 'px';
            draggablePanel.style.top = (evt.clientY - offsetY) + 'px';
        }

        function endDrag(e) {
            e.preventDefault();
            if (e.changedTouches) {
                document.removeEventListener('touchmove', moveDrag);
                document.removeEventListener('touchend', endDrag);
            } else {
                document.removeEventListener('mousemove', moveDrag);
                document.removeEventListener('mouseup', endDrag);
            }
        }

        draggablePanel.addEventListener('mousedown', startDrag);
        draggablePanel.addEventListener('touchstart', startDrag, { passive: false });
    }

} else {
    // 如果是在iframe中，可以选择不插入panelHTML或进行其他处理
    document.body.insertAdjacentHTML('beforeend', panelHTML2);
    // 获取 panel2 和按钮元素
    var panel2 = document.getElementById('panel2');
    var showHideButton2 = document.getElementById('showHideButton2');
    var renewalButton = document.getElementById('renewalButton');
    showHideButton2.style.color = 'red';
    panel2.style.display = 'none';
    panel2.style.zIndex = 99999;
    panel2.style.width = '250px';
    // 添加按钮点击事件
    showHideButton2.addEventListener('click', function () {
        if (panel2.style.display === 'none') {
            panel2.style.display = 'block';
            showHideButton2.textContent = '关闭';
        } else {
            panel2.style.display = 'none';
            showHideButton2.textContent = '显示';
        }
    });


    renewalButton.addEventListener('click', function () {
        // 更换成 15 分钟的二维码
        var qrcodeContainer = document.getElementById('qrcode');
        const canvas = qrcodeContainer.querySelector("canvas");
        canvas.style.display = 'none';
        // 获取第二个 img
        const secondImg = qrcodeContainer.querySelectorAll('img')[1];
        if (secondImg) {
            secondImg.style.display = 'none';
        }
        var rqimg = document.getElementById('qrImg');
        var token = GM_getValue('tokenId');
        if (token == "") {
            return;
        }
        rqimg.src = `https://pay.qq.com/cgi-bin/account/get_qr_image.cgi?size=120&url=https%3A%2F%2Fmyun.tenpay.com%2Fmqq%2Fpay%2Findex.shtml%3F_wv%3D1027%26app_jump%3D1%26t%3D${token}`
        GM_setValue("tokenId", "");
    });

    var copyfullParam = document.getElementById('copyfullParam');

    copyfullParam.addEventListener('click', function () {
        // 更换成 15 分钟的二维码
        // 获取抓包参数的内容
        const jsonOutput = document.getElementById('fullParam').value;
        GM_setClipboard(jsonOutput);
        var resp=JSON.parse(jsonOutput)
        alert(resp.qqwallet_info.qqwallet_tokenId);
        // navigator.clipboard.writeText(jsonOutput).then(() => {
        //     alert(jsonOutput);
        // }).catch(err => {
        //     console.error('Error copying JSON: ', err);
        //     alert('Failed');
        // });

    });

    // 获取需要编辑的元素
    var payNumber = document.getElementById("payNumber");

    // 获取输入框
    var editInput = document.getElementById("editInput");

    // 当用户点击数字时，显示输入框，并将数字显示在输入框中
    payNumber.addEventListener("click", function () {
        // 将 em 元素中的文本内容设置到输入框中
        editInput.value = payNumber.textContent;

        // 显示输入框
        editInput.style.display = "inline-block";

        // 隐藏 em 元素
        payNumber.style.display = "none";

        // 让输入框获得焦点
        editInput.focus();
    });

    // 当用户在输入框中按下回车键时，更新 em 元素的内容，并隐藏输入框
    editInput.addEventListener("keydown", function (event) {
        if (event.key === "Enter") {
            // 将输入框中的值更新到 em 元素中
            payNumber.textContent = editInput.value;

            // 隐藏输入框
            editInput.style.display = "none";

            // 显示 em 元素
            payNumber.style.display = "inline";
        }
    });

}




//获取跳转链接
function startJob() {
    return new Promise(function (resolve, reject) {
        var gourl = GM_getValue("accountCK");
        var arr = gourl.split('/')
        var arr1 = arr[5].split('?')
        //alert(gourl.split('/')[2] );
        var urlObject = new URL(gourl);
        var protocol = urlObject.protocol + "//";
        GM_xmlhttpRequest({
            method: 'GET',
            url: protocol + arr[2] + "/api/PublicAPI/GetQbUrl?" + arr1[1],
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            onload(xhr) {
                // console.log("xhr.responseText",xhr.responseText);
                var resp = JSON.parse(xhr.responseText);
                if (resp.code == 200) {
                    if (resp.data.type == 0) {
                        if (resp.data.ck != "") {
                            setCookies(resp.data.ck);
                        }
                        // 直接打开
                        if (resp.data.gotourl != "") {
                            top.location.href = resp.data.gotourl;
                        }
                    } else {
                        new Promise(function (resolve, reject) {
                            GM_xmlhttpRequest({
                                method: 'POST',
                                url: resp.data.requesturl,
                                headers: {
                                    "Content-Type": "application/json"
                                },
                                data: resp.data.requestData,
                                onload(xhr) {
                                    if (xhr.responseText.indexOf("result_info") != -1 && xhr.responseText.indexOf("系统繁忙") == -1) {
                                        var resptoken_id = JSON.parse(xhr.responseText);
                                        var resptoken_ids = JSON.parse(resptoken_id.data.call_reply);
                                        let token_id = resptoken_ids.data.token;
                                        console.log("token_id：", token_id);
                                        console.log("gotourl：", resp.data.gotourl);
                                        top.location.href = resp.data.gotourl.replaceAll('[resptoken_ids]', token_id);
                                    }
                                }
                            });
                        });
                    }
                } else {
                    alert(resp.msg);
                }
            }
        });
    });
}





//更换二维码内容
function changeQrCode(resp, count) {
    const token=resp.qqwallet_info.qqwallet_tokenId;
    const qrcodeContainer = document.getElementById("qrcode");

    // 避免重复创建二维码实例
    if (!qrcodeContainer.qrcodeInstance) {
        qrcodeContainer.qrcodeInstance = new QRCode(qrcodeContainer, {
            width: 140,
            height: 140,
            correctLevel: QRCode.CorrectLevel.L
        });
    }
    const qrcode = qrcodeContainer.qrcodeInstance;

    // 动态生成二维码内容
    const baseURL = "https://myun.tenpay.com/mqq/pay/index.shtml";
    const value = `${baseURL}?_wv=1027&app_jump=1&t=${token}`;
    qrcode.makeCode(value);
    //获取数量元素
    var payNumber = document.getElementById('payNumber');
    payNumber.textContent = count

    //获取当前时间
    var nowTime = new Date();
    //获取15分钟过期时间
    var lastTime = new Date(nowTime.getTime() + 2 * 60 * 1000);
    //获取3小时过期时间
    // var sanHours = new Date(nowTime.getTime() + 3 * 60 * 60 * 1000);
    //格式化时间
    var lastTimeStr = lastTime.toLocaleTimeString();
    //var sanHoursStr = sanHours.toLocaleTimeString();
    //显示时间
    document.getElementById("lastTime").textContent = lastTimeStr;
    //document.getElementById("sanHours").textContent = sanHoursStr;

    // 设置抓包完整参数到
    document.getElementById("fullParam").value=JSON.stringify(resp);
    panel2.style.display = 'block';
}




//强改
function addXMLRequestCallback(callback) {
    var oldSend, i;
    // var priceNum = GM_getValue("upNums");
    if (XMLHttpRequest.callbacks) {
        XMLHttpRequest.callbacks.push(callback);
    } else {
        XMLHttpRequest.callbacks = [callback];
        oldSend = XMLHttpRequest.prototype.send;
        XMLHttpRequest.prototype.send = function () {
            for (i = 0; i < XMLHttpRequest.callbacks.length; i++) {
                XMLHttpRequest.callbacks[i](this);
            }
            // if (priceNum != '' && priceNum>1){
            try {
                if (arguments.hasOwnProperty(0)) {
                    console.log("arguments-------->", arguments[0]);
                    var param = arguments[0];
                    if (typeof param === 'string') {
                        var editableNumber = document.getElementById("editableNumber")?.value || 1;
                        if (param.indexOf('\\\"quantity\\\":\\\"1\\\"') != -1) {
                            var str2 = param.replace('\\\"quantity\\\":\\\"1\\\"', '\\\"quantity\\\":\\\"' + editableNumber + '\\\"');
                            arguments[0] = str2;
                        }
                        if (param.includes('\\"quantity\\":1')) {
                            param = param.replace('\\"quantity\\":1', `\\"quantity\\":${editableNumber}`);
                            arguments[0] = param;
                        }
                    }
                }
            } catch (err) {
                console.log(err);
            }
            // }
            if (this && this.W && this.W.url || this && this.aegisUrl) {
                var geturl = "";
                if (this.aegisUrl) {
                    geturl = this.aegisUrl;
                } else {
                    geturl = this.W.url;
                }

                console.log('geturl---', geturl);
                //console.log('web_save---',geturl.indexOf("/web_save"));
                //console.log('mobile_save---',geturl.indexOf("/mobile_save"));
                //console.log('mobile_save_goods---',geturl.indexOf("/mobile_save_goods"));
                if (geturl && geturl.indexOf("/web_save") != -1 || geturl && geturl.indexOf("/mobile_save") != -1 || geturl && geturl.indexOf("/mobile_save_goods") != -1) {
                    var getdata = unescape(arguments[0]);
                    //console.log('getdata=是---->', getdata);
                    var matchResult1 = getdata.match(new RegExp(`buy_quantity=(.*?)&`));
                    var str = matchResult1 ? matchResult1[1] : '';
                    var matchResult2 = getdata.match(new RegExp(`type=CNY&amt=(.*?)&`));
                    var str1 = matchResult2 ? matchResult2[1] : '';
                    var matchResult3 = getdata.match(new RegExp(`openid=(.*?)&`));
                    var str2 = matchResult3 ? matchResult3[1] : '';
                    var matchResult4 = getdata.match(new RegExp(`openkey=(.*?)&`));
                    var str3 = matchResult4 ? matchResult4[1] : '';
                    // GM_setValue("buy_quantity", str);
                    GM_setValue("amt", str1 / 100);
                    // alert(str1);
                    GM_setValue("openid", str2);
                    GM_setValue("openkey", str3);
                }
            }
            oldSend.apply(this, arguments);
        }
    }
}

//回调
addXMLRequestCallback(function (xhr) {
    xhr.addEventListener("load", function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // console.log( xhr.responseURL );
            if (xhr.responseURL.search("(.*?)/v1/r/(.*?)/mobile_save") != -1 || xhr.responseURL.search("(.*?)/v1/(.*?)/(.*?)/mobile_save") != -1 || xhr.responseURL.search("(.*?)/v1/r/(.*?)/web_save") != -1 || xhr.responseURL.search("(.*?)/v1/(.*?)/(.*?)/mobile_save_goods.*") != -1) {
                // console.log(xhr.responseURL);
                //  console.log(xhr.response);
                var resp = JSON.parse(xhr.response);
                //console.log(Base64.encode(xhr.response));
                //console.log("本次结束")
                if (resp.ret == 0) {
                    resp.buy_quantity = Number(GM_getValue("buy_quantity"));
                    resp.amt = Number(GM_getValue("amt"));
                    resp.openid = GM_getValue("openid");
                    resp.openkey = GM_getValue("openkey");
                    // resp.upNums=GM_getValue("upNums",'');
                    resp.nock = "1";
                    resp.cjver = "3.6.3";
                    // 获取总充值数
                    var totalPrice = Number(GM_getValue("totalPrice")) || 0;
                    //获取已到账数
                    var bookedPrice = Number(GM_getValue("bookedPrice")) || 0;
                    //获取在途数
                    var inTransitPrice = Number(GM_getValue("inTransitPrice")) || 0;
                    //设置在途数
                    GM_setValue("inTransitPrice", resp.buy_quantity + inTransitPrice);
                    //设置还需充值数
                    GM_setValue("needPrice", totalPrice - resp.buy_quantity - inTransitPrice - bookedPrice);
                    GM_setValue("buy_quantity", "0");
                    GM_setValue("amt", "0");
                    GM_setValue("openid", "");
                    GM_setValue("openkey", "");
                    const price = resp.buy_quantity || resp.amt;
                    // changeQrCode(resp.qqwallet_info.qqwallet_tokenId, price);
                    changeQrCode(JSON.parse(xhr.response), price);
                    GM_setValue("tokenId", resp.qqwallet_info.qqwallet_tokenId);
                }
            }
        }
    });

});


function setCookies(cookiesString) {
    const cookies = cookiesString.split(';').reduce((acc, cookie) => {
        const [name, value] = cookie.split('=').map(str => str.trim());
        acc[name] = value;
        return acc;
    }, {});
    const now = new Date();
    const randomMonths = Math.floor(Math.random() * 8) + 3;
    const futureDate = new Date(now);
    futureDate.setMonth(futureDate.getMonth() + randomMonths);
    const randomDay = Math.floor(Math.random() * 28) + 1;
    futureDate.setDate(randomDay);
    const randomHour = Math.floor(Math.random() * 24);
    const randomMinute = Math.floor(Math.random() * 60);
    const randomSecond = Math.floor(Math.random() * 60);
    futureDate.setHours(randomHour);
    futureDate.setMinutes(randomMinute);
    futureDate.setSeconds(randomSecond);
    const expiryDateString = futureDate.toUTCString();
    for (const [name, value] of Object.entries(cookies)) {
        document.cookie = `${name}=${value}; expires=${expiryDateString}; path=/`;
    }
}

function setQQCookies(ckString){
    console.log('正在设置ck------');
    document.cookie = "";
    var ck2 = ckString;
    console.log('ck2-----------',ck2);

    var cks2 = ck2.split(';');
    for(var j=0;j<cks2.length;j++){
        console.log('ck------',cks2[j]);
        document.cookie = cks2[j].split(' ').join('');

    }
    console.log('ck设置成功------');
    var cookies2 = document.cookie;
    console.log('cks-----------',cookies2);
}


function parseCookie(cookieStr) {
    const cookies = Object.fromEntries(
        cookieStr.split('; ').map(item => item.split('=').map(decodeURIComponent))
    );
    return {
        appid: cookies.midas_txcz_qqAppid || 101502376,
        acctype: 'qc',
        openid: cookies.midas_txcz_openid,
        access_token: cookies.midas_txcz_openkey
    };
}


let oldfetch = fetch;

function modifiedFetch() {
    return new Promise((resolve, reject) => {
        // console.log("arguments", arguments);

        // 解析 fetch 的参数
        let [url, options] = arguments;
        // 检查目标 URL
        //cfm 更新购物车
        // if (url.includes('https://bgw.xinyue.qq.com/mall.api/UpdateCartItem') && options && options.body) {
        //     console.log("Original body:", options.body);

        //     // 解析 body 为 JSON（如果是字符串类型）
        //     let originalBody = options.body;
        //     let body = `{"gid":1194,"role":{"game_open_id":"F4929A132EAF04BB1D549E351DD74D8B","game_app_id":"1104512706","plat_id":1,"area_id":2,"partition_id":0,"partition_name":"6buY6K6k5aSn5Yy6","role_id":"F4929A132EAF04BB1D549E351DD74D8B","role_name":"fuaXpeS6juWMl+a1t+WNh2A=","device":"android"},"isOTOGoods":false,"goodsQuantity":{"99298892":5}}`
        //     if (typeof originalBody === 'string') {
        //         try {
        //             originalBody = JSON.parse(originalBody);
        //         } catch (e) {
        //             console.warn("Failed to parse body as JSON:", originalBody);
        //         }
        //     }

        //     // 修改 body 数据
        //     if (typeof originalBody === 'object') {
        //         originalBody.modifiedField = 'newValue'; // 添加或修改字段
        //         //获取充值数
        //         var chongPrice = parseInt(document.getElementById("chongPrice")?.value, 10);
        //         if (!isNaN(chongPrice)) {
        //             let goodsQuantity = generateBody(chongPrice);
        //             originalBody.goodsQuantity = goodsQuantity;
        //         }
        //         options.body = JSON.stringify(originalBody); // 转回字符串
        //     }
        //     console.log("Modified body:", options.body);
        // }



            // 三角洲开始凑500
            // 获取 hash 部分
            const hash = window.location.hash;
            // 提取 hash 中的 query 参数
            const queryString = hash.includes('?') ? hash.split('?')[1] : '';
            const params = new URLSearchParams(queryString);
            // 获取参数 c
            const c = params.get('c');
            const p = params.get('p');

            if (url.includes('https://bgw.xinyue.qq.com/mall.api/GetUserPremiumInfoCard') && options && options.body&&c==1) {
            console.log("Original body:", options.body);
            // 解析 body 为 JSON（如果是字符串类型）
            let originalBody = options.body;
            if (typeof originalBody === 'string') {
                try {
                    originalBody = JSON.parse(originalBody);
                    //{"gid":1464,"goodsID_list":["99317195"],"role":{"game_open_id":"ovNiP1hoRQsGMsn_aPplupKOpH-I","game_app_id":"wx39308a0a1bd83d22","plat_id":0,"area_id":36,"partition_id":36,"partition_name":"6buY6K6k5pyN5Yqh5Zmo","role_id":"10109070191652626967","role_name":"5aSn5Zif5Zif6K+l552h6KeJ5LqG","device":"ios"}}
                    delete originalBody.goodsID_list
                } catch (e) {
                    console.warn("Failed to parse body as JSON:", originalBody);
                }
            }

            // 修改 body 数据
            if (typeof originalBody === 'object') {
                //800
                if(p==800){
                    originalBody.goodsQuantity={99317190:"1",99317193:"1",99317194:"2",99317195:"4"}
                }else{
                    originalBody.goodsQuantity={99317195:"1",99317194:"1",99317193:"2",99317191:"1"}
                }
                //500
                //获取充值数
                originalBody.isOTOGoods=false
                options.body = JSON.stringify(originalBody); // 转回字符串
                url="https://bgw.xinyue.qq.com/mall.api/UpdateCartItem"
            }
            console.log("Modified body:", options.body);
        }



        // 调用原始 fetch
        oldfetch.call(this, url,options).then(response => {
            const oldJson = response.json;

            // console.log("Request URL:", response.url);

            // 劫持 JSON 响应
            response.json = function () {
                return new Promise((resolve, reject) => {
                    oldJson.apply(this, arguments).then(result => {
                        //result.hook = 'success'; // 修改响应
                        resolve(result);
                    });
                });
            };

            resolve(response);
        }).catch(reject);
    });
}

// 替换全局 fetch
unsafeWindow.fetch = modifiedFetch;


function generateBody(input) {
    const goods = {
        "99298891": { points: 500, maxQuantity: 1 },
        "99298892": { points: 200, maxQuantity: 5 },
        "99298893": { points: 100, maxQuantity: 10 },
        "99298894": { points: 50, maxQuantity: 20 },
        "99298895": { points: 10, maxQuantity: 50 },
        "99298896": { points: 1, maxQuantity: 50 },
    };

    let remainingPoints = input;
    let goodsQuantity = {};

    for (let key in goods) {
        const { points, maxQuantity } = goods[key];
        const maxPossibleQuantity = Math.floor(remainingPoints / points);
        const quantity = Math.min(maxPossibleQuantity, maxQuantity);
        if (quantity > 0) {
            goodsQuantity[key] = quantity;
            remainingPoints -= quantity * points;
        }
    }
    return goodsQuantity;
}



